package cn.itcast.eduservice.controller;


import cn.itcast.baseservice.exceptionhandle.GuliException;
import cn.itcast.commonutils.R;
import cn.itcast.eduservice.client.VodClient;
import cn.itcast.eduservice.entity.EduVideo;
import cn.itcast.eduservice.service.EduVideoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author Duanzihuang
 * @since 2020-05-19
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {
    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private VodClient vodClient;

    @ApiOperation(value = "新增小节")
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    @ApiOperation(value = "获取小节信息")
    @GetMapping("getVideo/{id}")
    public R getVideo(@PathVariable String id) {
        EduVideo video = eduVideoService.getById(id);
        return R.ok().data("video",video);
    }

    @ApiOperation(value = "修改小节")
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }

    @ApiOperation(value = "删除小节")
    @DeleteMapping("deleteVideo/{id}")
    public R deleteVideo(@PathVariable String id) {
        // 根据小节id，查询出小节中的视频id
        EduVideo eduVideo = eduVideoService.getById(id);
        String videoId = eduVideo.getVideoSourceId();

        if (!StringUtils.isEmpty(videoId)){
            // 通过远程调用，删除小节对应的视频
            R result = vodClient.removeAliyunVideo(videoId);
            if (result.getCode() == 20001) {
                throw new GuliException(20001,"删除视频出错,熔断器...");
            }
        }

        boolean b = eduVideoService.removeById(id);
        if (!b) {
            throw new GuliException(20001,"删除小节失败");
        }

        return R.ok();
    }
}

